package com.css.fxfzypg.modules.saresults.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.saresults.entity.DzqhGroundMotionParametersEntity;
import com.css.fxfzypg.modules.saresults.param.MotionParametersParam;
import com.css.fxfzypg.modules.saresults.repository.GroundMotionParametersRepository;
import com.css.fxfzypg.modules.saresults.service.GroundMotionParametersService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GroundMotionParametersServiceImpl implements GroundMotionParametersService {

    @Autowired
    private GroundMotionParametersRepository groundMotionParametersRepository;

    @Override
    public RestResponse importData(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Object> title = reader.readRow(0);
            String titleName = "[ID, 省, 市, 县区, 乡镇街道, 乡镇/街道, 峰值加速度/g, 反应谱特征周期／s, 经度, 纬度, 区划代码]";
            if (!titleName.equals(title.toString())) {
                return RestResponse.fail("导入失败，请检查表头是否改动");
            }

            List<List<Object>> read = reader.read(1, reader.getRowCount());
            if (read.size() == 0) {
                return RestResponse.fail("导入失败，表格中无数据");
            }

            //查询重复数据
            List<Object> ids = reader.readColumn(0, 1);
            if (getDuplicateData(ids).getCode() != 200) {
                return RestResponse.fail(getDuplicateData(ids).getMessage());
            }
            //数据校验
            RestResponse rs = groundMotionParameters(read.size(), read);
            if (rs.getCode() != 200) {
                return RestResponse.fail(rs.getMessage());
            }
            for (List<Object> objects : read) {
                DzqhGroundMotionParametersEntity parameters = new DzqhGroundMotionParametersEntity();
                parameters.setId(Long.parseLong(objects.get(0).toString()));
                parameters.setProvince(objects.get(1).toString());
                parameters.setCity(objects.get(2).toString());
                parameters.setCounty(objects.get(3).toString());
                parameters.setTownship(objects.get(4).toString());
                parameters.setType(objects.get(5).equals("街道") ? "1" : "0");
                parameters.setPeakAcceleration(new BigDecimal(objects.get(6).toString()));
                parameters.setResponseSpectrum(new BigDecimal(objects.get(7).toString()));
                parameters.setLongitude(Double.parseDouble(objects.get(8).toString()));
                parameters.setLatitude(Double.parseDouble(objects.get(9).toString()));
                parameters.setZoningCode(Long.valueOf(objects.get(10).toString()));
                parameters.setCreateUser(PlatformSessionContext.getUserID());
                parameters.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
                parameters.setGmpCode(getTime() + parameters.getZoningCode());
                parameters.setGmpId(UUIDGenerator.getUUID());
                parameters.setIsDelete("0");
                parameters.setListType("0");
                groundMotionParametersRepository.saveData(parameters);
            }
            return RestResponse.succeed("导入成功!");
        } catch (Exception e) {
            String errorMessage = "导入失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    /**
     * 校验参数
     *
     * @param size
     * @param data
     * @return
     */
    private RestResponse groundMotionParameters(int size, List<List<Object>> data) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < size; i++) {
            List<Object> objects = data.get(i);
            if (StringUtils.isBlank(objects.get(0).toString())) sb.append("第" + (i + 2) + "行的{ID}不能为空！");
            if (StringUtils.isBlank(objects.get(1).toString()))
                sb.append("第" + (i + 2) + "行的{省}不能为空！");
            if (StringUtils.isBlank(objects.get(2).toString()))
                sb.append("第" + (i + 2) + "行的{市}不能为空！");
            if (StringUtils.isBlank(objects.get(3).toString()))
                sb.append("第" + (i + 2) + "行的{区县}不能为空！");
            if (StringUtils.isBlank(objects.get(4).toString()))
                sb.append("第" + (i + 2) + "行的{乡镇街道}不能为空！");
            if (StringUtils.isBlank(objects.get(5).toString()))
                sb.append("第" + (i + 2) + "行的{乡镇/街道}不能为空！");
            if (StringUtils.isBlank(objects.get(6).toString()))
                sb.append("第" + (i + 2) + "行的{峰值加速度/g}不能为空！");
            if (StringUtils.isBlank(objects.get(7).toString()))
                sb.append("第" + (i + 2) + "行的{反应谱特征周期/s}不能为空！");
            if (StringUtils.isBlank(objects.get(8).toString()))
                sb.append("第" + (i + 2) + "行的{经度}不能为空！");
            if (StringUtils.isBlank(objects.get(9).toString()))
                sb.append("第" + (i + 2) + "行的{纬度}不能为空！");
            if (StringUtils.isBlank(objects.get(10).toString()))
                sb.append("第" + (i + 2) + "行的{区划代码}不能为空！");
        }
        if (!StringUtils.isBlank(sb)) {
            return RestResponse.fail(sb.toString());
        } else {
            return RestResponse.succeed();
        }
    }

    /**
     * 获取年月日
     */
    private static String getTime() {
        LocalDate currentDate = LocalDate.now();
        return currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    }

    @Override
    public RestResponse queryMotionParameters(MotionParametersParam motionParametersParam, HttpServletRequest request,String geom) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            return RestResponse.succeed(groundMotionParametersRepository.queryMotionParameters(motionParametersParam, page, size,geom));
        } catch (NumberFormatException e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getGmpById(String gmpId) {
        try {
            DzqhGroundMotionParametersEntity entity = groundMotionParametersRepository.getGmpByGmpId(gmpId);
            //全省乡镇个数查询
            entity.setProvinceNumber(groundMotionParametersRepository.getProvinceNumber(entity.getProvince()));
            //全市乡镇个数
            entity.setCityNumber(groundMotionParametersRepository.getCityNumber(entity.getCity()));
            //全区县乡镇个数
            entity.setCountyNumber(groundMotionParametersRepository.getCountyNumber(entity.getCounty()));
            return RestResponse.succeed(entity);
        } catch (Exception e) {
            String errorMessage = "查看失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse demolitionOrSave(DzqhGroundMotionParametersEntity entity) {
        try {
            entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setGmpCode(getTime() + entity.getZoningCode());
            entity.setIsDelete("0");
            entity.setListType(PlatformObjectUtils.isEmpty(entity.getGmpId()) ? "0" : "1");
            //如果是撤设，需要逻辑删除变更前的数据
            if (PlatformObjectUtils.isNotEmpty(entity.getGmpId())) {
                entity.setOriginalId(entity.getGmpId());
                groundMotionParametersRepository.deleteDataById(entity.getGmpId());
            }else {
                //如果是新设数据，需要判断id是否重复
                DzqhGroundMotionParametersEntity entity1 = groundMotionParametersRepository.getGmpById(entity.getId());
                if(entity1!=null){
                    return RestResponse.fail("失败,ID重复!");
                }
            }
            entity.setListType("1");
            entity.setGmpId(UUIDGenerator.getUUID());
            groundMotionParametersRepository.saveData(entity);
            return RestResponse.succeed("成功!");
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse restoreData(String reasonForChange, String approvalDocuments, String originalId,String gmpId,String type) {
        try {
            //先删除撤设后的数据
            groundMotionParametersRepository.deleteDataById(gmpId);
            //查询原数据的id
            DzqhGroundMotionParametersEntity orderEntity = groundMotionParametersRepository.getGmpByOriginalId(originalId);
            //将原始数据恢复
            String gmpCode = getTime() + orderEntity.getId();
            orderEntity.setGmpCode(gmpCode);
            orderEntity.setReasonForChange(reasonForChange);
            orderEntity.setApprovalDocuments(approvalDocuments);
            orderEntity.setUpdateUser(PlatformSessionContext.getUserID());
            orderEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
            orderEntity.setType(type);
            orderEntity.setIsDelete("0");
            orderEntity.setListType("1");
            orderEntity.setOriginalId(null);
            groundMotionParametersRepository.updateDataByOriginalId(orderEntity);
            return RestResponse.succeed("成功!");
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public void exportData(MotionParametersParam param, HttpServletResponse response) {
        try {
            List<DzqhGroundMotionParametersEntity> list = groundMotionParametersRepository.getMotionParameters(param);
            FileUtil.exportExcel(list, "地震动参数信息", "地震动参数", DzqhGroundMotionParametersEntity.class, "地震动参数列表.xlsx", response);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 查询重复数据
     * @param ids
     * @return
     */
    private RestResponse getDuplicateData(List<Object> ids){

        List<Long> idList1 = ids.stream()
                .map(obj -> (Long) obj)
                .collect(Collectors.toList());

        List<Long> idList2 = groundMotionParametersRepository.getAllId();

        Set<Long> set1 = new HashSet<>(idList1);
        Set<Long> set2 = new HashSet<>(idList2);

        Set<Long> resultSet = set1.stream()
                .filter(set2::contains)
                .collect(Collectors.toSet());

        if(PlatformObjectUtils.isNotEmpty(resultSet)){
            return RestResponse.fail("失败! ID为  "+resultSet+"  的数据已添加,请勿重复添加");
        }
        return RestResponse.succeed();
    }

    @Override
    public RestResponse deleteData(String ids) {
        try {
            for (String id : ids.split(",")) {
                groundMotionParametersRepository.deleteDataById(id);
            }
            return RestResponse.succeed("删除成功");
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getNumberByRegion(String province, String city, String county) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            //全省乡镇个数查询
            map.put("province",groundMotionParametersRepository.getProvinceNumber(province));
            //全市乡镇个数
            map.put("city",groundMotionParametersRepository.getCityNumber(city));
            //全区县乡镇个数
            map.put("county",groundMotionParametersRepository.getCountyNumber(county));
            return RestResponse.succeed(map);
        } catch (Exception e) {
            String errorMessage = "失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public RestResponse getByGeom(MotionParametersParam motionParametersParam,String geom) {
        return RestResponse.succeed(groundMotionParametersRepository.getByGeom(motionParametersParam,geom));
    }
}
